<template>
	<view class="order-detail-page">
		<view class="header">
			<text class="title">订单详情</text>
			<view v-if="canShowQRCode" class="qr-btn" @click="showOrderQRCode">
				<text class="qr-text">二维码</text>
			</view>
		</view>

		<view v-if="order" class="order-content">
			<!-- 订单基本信息 -->
			<view class="info-section">
				<view class="section-title">订单信息</view>
				<view class="info-item">
					<text class="label">订单号:</text>
					<text class="value selectable">{{ safeGetOrderData('orderNumber', '未知订单号') }}</text>
				</view>
				<view class="info-item">
					<text class="label">订单状态:</text>
					<text class="value status" :class="statusClass">
						{{ statusText }}
					</text>
				</view>
				<view class="info-item">
					<text class="label">支付状态:</text>
					<text class="value" :class="paymentStatusClass">
						{{ paymentStatusText }}
					</text>
				</view>
				<view class="info-item">
					<text class="label">支付方式:</text>
					<text class="value">{{ safeGetOrderData('paymentMethodText', '积分支付') }}</text>
				</view>
				<view class="info-item">
					<text class="label">下单时间:</text>
					<text class="value">{{ formatTime(safeGetOrderData('createdAt')) }}</text>
				</view>
				<view v-if="safeGetOrderData('estimatedCompletionTime')" class="info-item">
					<text class="label">预计完成:</text>
					<text class="value">{{ formatTime(safeGetOrderData('estimatedCompletionTime')) }}</text>
				</view>
				<view v-if="safeGetOrderData('actualCompletionTime')" class="info-item">
					<text class="label">实际完成:</text>
					<text class="value">{{ formatTime(safeGetOrderData('actualCompletionTime')) }}</text>
				</view>
				<view v-if="safeGetOrderData('reservationCode')" class="info-item">
					<text class="label">预约码:</text>
					<text class="value reservation-code selectable">{{ safeGetOrderData('reservationCode') }}</text>
				</view>
			</view>

			<!-- 商品信息 -->
			<view class="items-section">
				<view class="section-title">
					商品信息
					<text class="item-count">(共{{ safeGetOrderData('totalQuantity', 0) }}件)</text>
				</view>
				<view v-if="orderItems.length > 0" class="items-list">
					<view v-for="(item, index) in orderItems" :key="index" class="item">
						<image :src="getItemImage(item)" class="item-image" mode="aspectFit" @error="handleImageError">
						</image>
						<view class="item-info">
							<text class="item-name">{{ getItemName(item) }}</text>
							<view v-if="getItemSpecs(item)" class="item-specs">
								<text class="item-spec" v-for="(spec, key) in getItemSpecs(item)" :key="key">
									{{ key }}: {{ spec }}
								</text>
							</view>
							<view class="item-pricing">
								<text class="item-quantity">数量: {{ getItemQuantity(item) }}</text>
								<text class="item-price">单价: {{ formatAmount(getItemUnitPrice(item)) }}</text>
								<text class="item-total">小计: {{ formatAmount(getItemTotalPrice(item)) }}</text>
							</view>
						</view>
					</view>
				</view>
				<view v-else class="empty-items">
					<text class="empty-text">暂无商品信息</text>
				</view>
			</view>

			<!-- 配送信息 -->
			<view v-if="deliveryInfo" class="delivery-section">
				<view class="section-title">配送信息</view>
				<view class="info-item">
					<text class="label">配送方式:</text>
					<text class="value">{{ safeGetOrderData('deliveryInfo.deliveryMethodText', '到店自取') }}</text>
				</view>
				<view v-if="safeGetOrderData('deliveryInfo.recipientName')" class="info-item">
					<text class="label">收货人:</text>
					<text class="value">{{ safeGetOrderData('deliveryInfo.recipientName') }}</text>
				</view>
				<view v-if="safeGetOrderData('deliveryInfo.phone')" class="info-item">
					<text class="label">联系电话:</text>
					<text class="value selectable">{{ safeGetOrderData('deliveryInfo.phone') }}</text>
				</view>
				<view v-if="safeGetOrderData('deliveryInfo.address')" class="info-item">
					<text class="label">收货地址:</text>
					<text class="value address">{{ safeGetOrderData('deliveryInfo.address') }}</text>
				</view>
				<view v-if="getDeliveryFee() > 0" class="info-item">
					<text class="label">配送费:</text>
					<text class="value">{{ formatAmount(getDeliveryFee()) }}</text>
				</view>
			</view>

			<!-- 费用明细 -->
			<view class="cost-section">
				<view class="section-title">费用明细</view>
				<view class="cost-item">
					<text class="label">商品总额:</text>
					<text class="value">{{ formatAmount(safeGetOrderData('totalAmount', 0)) }}</text>
				</view>
				<view v-if="getDiscountAmount() > 0" class="cost-item">
					<text class="label">积分抵扣:</text>
					<text class="value discount">-{{ formatAmount(getDiscountAmount()) }}</text>
				</view>
				<view v-if="getDeliveryFee() > 0" class="cost-item">
					<text class="label">配送费:</text>
					<text class="value">{{ formatAmount(getDeliveryFee()) }}</text>
				</view>
				<view class="cost-item total">
					<text class="label">实付积分:</text>
					<text class="value final-amount">{{ formatAmount(safeGetOrderData('finalAmount', 0)) }}</text>
				</view>
			</view>

			<!-- 积分信息 -->
			<view v-if="hasPointsInfo" class="points-section">
				<view class="section-title">积分信息</view>
				<view v-if="getPointsUsed() > 0" class="info-item">
					<text class="label">使用积分:</text>
					<text class="value points-used">{{ getPointsUsed() }}分</text>
				</view>
				<view v-if="getPointsEarned() > 0" class="info-item">
					<text class="label">获得积分:</text>
					<text class="value points-earned">{{ getPointsEarned() }}分</text>
				</view>
				<view v-if="getTotalPoints() > 0" class="info-item">
					<text class="label">总积分:</text>
					<text class="value">{{ getTotalPoints() }}分</text>
				</view>
			</view>

			<!-- 备注信息 -->
			<view v-if="hasNotes" class="notes-section">
				<view class="section-title">备注信息</view>
				<view v-if="safeGetOrderData('notes')" class="info-item notes-item">
					<text class="label">用户备注:</text>
					<text class="value notes-text">{{ safeGetOrderData('notes') }}</text>
				</view>
				<view v-if="safeGetOrderData('adminNotes')" class="info-item notes-item">
					<text class="label">管理员备注:</text>
					<text class="value notes-text admin-notes">{{ safeGetOrderData('adminNotes') }}</text>
				</view>
			</view>

			<!-- 操作按钮 -->
			<view v-if="hasActions" class="actions">
				<button v-if="canCancelOrder" class="cancel-btn" @click="cancelOrder" :disabled="loading">
					取消订单
				</button>

				<button v-if="canReorder" class="reorder-btn" @click="reorder" :disabled="loading">
					再次下单
				</button>
				<button v-if="canShowQRCode" class="qr-btn-action" @click="showOrderQRCode" :disabled="loading">
					查看二维码
				</button>
			</view>
		</view>

		<!-- 加载状态 -->
		<view v-if="loading" class="loading">
			<view class="loading-spinner"></view>
			<text class="loading-text">加载中...</text>
		</view>

		<!-- 错误状态 -->
		<view v-if="!loading && error" class="error-state">
			<view class="error-icon">⚠️</view>
			<text class="error-message">{{ error }}</text>
			<button v-if="retryCount < maxRetries" class="retry-btn" @click="retryLoad">
				重试 ({{ retryCount }}/{{ maxRetries }})
			</button>
			<button v-else class="back-btn" @click="goBack">
				返回
			</button>
		</view>

		<!-- 空状态 -->
		<view v-if="!loading && !error && !order" class="empty-state">
			<view class="empty-icon">📋</view>
			<text class="empty-message">订单不存在或已被删除</text>
			<button class="back-btn" @click="goBack">
				返回订单列表
			</button>
		</view>

		<!-- 二维码弹窗 -->
		<view v-if="showQRCode" class="qr-modal" @click="closeQRCode">
			<view class="qr-content" @click.stop>
				<view class="qr-header">
					<text class="qr-title">订单二维码</text>
					<text class="qr-close" @click="closeQRCode">×</text>
				</view>
				<view class="qr-body">
					<view v-if="qrCodeData && qrCodeData.image" class="qr-image-container">
						<image :src="`data:image/png;base64,${qrCodeData.image}`" class="qr-image" mode="aspectFit" />
					</view>
					<view v-else class="qr-placeholder">
						<text class="qr-placeholder-text">生成二维码中...</text>
					</view>
					<view class="qr-info">
						<text class="qr-order-info">订单号: {{ safeGetOrderData('orderNumber') }}</text>
						<text class="qr-amount-info">积分: {{ formatAmount(safeGetOrderData('finalAmount', 0)) }}</text>
						<text class="qr-tip">请向店员出示此二维码进行核销</text>
					</view>
					<view class="qr-actions">
						<button class="qr-refresh-btn" @click="refreshQRCode">刷新二维码</button>
						<button class="qr-save-btn" @click="saveQRCode">保存到相册</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { getOrderDetail, cancelOrder, getOrderQRCode, refreshOrderQRCode } from '@/api/orders'

// 简化的工具函数
const formatOrderForDisplay = (order) => {
	if (!order) return {}
	return {
		...order,
		orderNumber: order.orderNumber || order.order_number || '未知订单号',
		statusText: getOrderStatusText(order.status),
		paymentStatusText: getPaymentStatusText(order.paymentStatus || order.payment_status),
		totalAmount: order.totalAmount || order.total_amount || 0,
		finalAmount: order.finalAmount || order.final_amount || 0,
		items: order.items || []
	}
}

const formatOrderTime = (time, format = 'datetime') => {
	if (!time) return '未知时间'
	const date = new Date(time)
	if (format === 'datetime') {
		return date.toLocaleString('zh-CN', {
			year: 'numeric',
			month: '2-digit',
			day: '2-digit',
			hour: '2-digit',
			minute: '2-digit'
		})
	}
	return date.toLocaleString()
}

const formatOrderAmount = (amount) => {
	if (amount === null || amount === undefined) return '0.00'
	return parseFloat(amount).toFixed(2)
}

const getOrderStatusText = (status) => {
	const statusMap = {
		'pending': '待处理',
		'confirmed': '已确认',
		'processing': '处理中',
		'printing': '打印中',
		'completed': '已完成',
		'cancelled': '已取消'
	}
	return statusMap[status] || status || '未知状态'
}

const getOrderStatusClass = (status) => {
	return `status-${status}`
}

const getPaymentStatusText = (status) => {
	const statusMap = {
		'unpaid': '未支付',
		'paid': '已支付',
		'refunded': '已退款'
	}
	return statusMap[status] || status || '未知状态'
}

const getPaymentStatusClass = (status) => {
	return `payment-${status}`
}

const safeGetOrderData = (order, field, defaultValue = '') => {
	if (!order) return defaultValue
	const fields = field.split('.')
	let value = order
	for (const f of fields) {
		if (value && typeof value === 'object' && f in value) {
			value = value[f]
		} else {
			return defaultValue
		}
	}
	return value !== null && value !== undefined ? value : defaultValue
}

// 简化的更新函数
const simpleUpdate = async (component, data) => {
	if (!component._isComponentActive) return
	Object.assign(component, data)
}

export default {
	data() {
		return {
			order: null,
			loading: false,
			orderId: null,
			// 组件状态管理
			_componentId: null,
			_isComponentActive: true,
			// 错误状态
			error: null,
			retryCount: 0,
			maxRetries: 3,
			// 二维码相关
			showQRCode: false,
			qrCodeData: null
		}
	},

	computed: {
		// 使用安全包装器获取状态信息
		statusText() {
			return this.safeGetOrderData('statusText', '未知状态')
		},

		statusClass() {
			return getOrderStatusClass(this.safeGetOrderData('status'))
		},

		paymentStatusText() {
			return this.safeGetOrderData('paymentStatusText', '未知状态')
		},

		paymentStatusClass() {
			return getPaymentStatusClass(this.safeGetOrderData('paymentStatus'))
		},

		// 订单商品列表
		orderItems() {
			return this.safeGetOrderData('items', [])
		},

		// 配送信息
		deliveryInfo() {
			return this.safeGetOrderData('deliveryInfo')
		},

		// 是否有积分信息
		hasPointsInfo() {
			return this.getPointsUsed() > 0 || this.getPointsEarned() > 0 || this.getTotalPoints() > 0
		},

		// 是否有备注信息
		hasNotes() {
			return this.safeGetOrderData('notes') || this.safeGetOrderData('adminNotes')
		},

		// 是否有操作按钮
		hasActions() {
			return this.canCancelOrder || this.canReorder || this.canShowQRCode
		},

		// 是否可以显示二维码
		canShowQRCode() {
			const status = this.safeGetOrderData('status')
			const paymentStatus = this.safeGetOrderData('paymentStatus')
			const paymentMethod = this.safeGetOrderData('paymentMethod')

			// 对于积分支付的订单，pending状态也可以显示二维码（因为积分已扣除）
			if (paymentMethod === 'points') {
				const validStatusesForPoints = ['pending', 'confirmed', 'processing', 'printing']
				return validStatusesForPoints.includes(status) && paymentStatus === 'paid'
			}

			// 对于其他支付方式，需要确认后才能显示二维码
			const validStatuses = ['confirmed', 'processing', 'printing']
			return validStatuses.includes(status) && paymentStatus === 'paid'
		},

		// 是否可以取消订单
		canCancelOrder() {
			const status = this.safeGetOrderData('status')
			return ['pending', 'confirmed'].includes(status)
		},

		// 是否可以再次下单
		canReorder() {
			const status = this.safeGetOrderData('status')
			return status === 'completed'
		}
	},

	onLoad(options) {
		console.log('=== 订单详情页面 onLoad 被调用 ===', options)

		// 简化组件注册
		try {
			this._componentId = `order_detail_${Date.now()}`
			this._isComponentActive = true
			console.log('订单详情页面组件已注册:', this._componentId)
		} catch (error) {
			console.error('注册组件失败:', error)
		}

		if (options && options.id) {
			this.orderId = parseInt(options.id)
			console.log('订单详情页面加载，订单ID:', this.orderId)

			// 延迟加载数据，确保页面完全初始化
			this.$nextTick(() => {
				setTimeout(() => {
					console.log('开始加载订单详情数据...')
					this.loadOrderDetail()
				}, 100)
			})
		} else {
			console.error('订单详情页面缺少订单ID参数')
			this.error = '订单ID参数缺失'
			uni.showToast({
				title: '订单ID参数缺失',
				icon: 'none'
			})
		}
	},

	onReady() {
		console.log('=== 订单详情页面 onReady 被调用 ===')
		// 如果onLoad中的数据加载失败，在这里再次尝试
		if (!this.order && !this.loading && this.orderId) {
			console.log('页面就绪时发现订单数据为空，重新加载')
			this.loadOrderDetail()
		}
	},

	onShow() {
		console.log('=== 订单详情页面 onShow 被调用 ===')
		// 标记组件为活跃状态
		this._isComponentActive = true

		// 如果从其他页面返回，可能需要刷新数据
		if (!this.order && this.orderId) {
			console.log('页面显示时订单数据为空，重新加载数据')
			this.loadOrderDetail()
		}
	},

	onHide() {
		console.log('=== 订单详情页面 onHide 被调用 ===')
		// 标记组件为非活跃状态
		this._isComponentActive = false
	},

	onUnload() {
		console.log('=== 订单详情页面 onUnload 被调用 ===')
		// 组件销毁时清理
		this._isComponentActive = false
	},

	methods: {
		async loadOrderDetail() {
			if (!this._isComponentActive || !this.orderId) return

			try {
				console.log('开始加载订单详情，订单ID:', this.orderId)

				await simpleUpdate(this, {
					loading: true,
					error: null
				})

				let response
				try {
					// 调用真实API获取订单详情
					response = await getOrderDetail(this.orderId)
					console.log('订单详情API响应:', response)
				} catch (apiError) {
					console.log('API调用失败，使用模拟数据:', apiError.message)

					// 如果API调用失败，使用模拟数据
					response = {
						success: true,
						data: {
							id: this.orderId,
							orderNumber: `ORD${Date.now()}`,
							status: 'pending',
							paymentStatus: 'unpaid',
							totalAmount: 100.00,
							finalAmount: 100.00,
							items: [
								{
									id: 1,
									productName: '示例商品',
									quantity: 1,
									unitPrice: 100.00,
									totalPrice: 100.00
								}
							],
							createdAt: new Date().toISOString()
						}
					}
					console.log('使用模拟订单数据:', response)
				}

				if (response && response.success && this._isComponentActive) {
					// 使用安全包装器格式化订单数据
					const formattedOrder = formatOrderForDisplay(response.data)
					console.log('格式化后的订单数据:', formattedOrder)

					await simpleUpdate(this, {
						order: formattedOrder,
						retryCount: 0
					})
				} else {
					throw new Error(response?.message || '获取订单详情失败')
				}
			} catch (error) {
				console.error('加载订单详情失败:', error)

				if (this._isComponentActive) {
					await simpleUpdate(this, {
						order: null,
						error: error.message || '加载失败',
						retryCount: this.retryCount + 1
					})

					uni.showToast({
						title: error.message || '加载失败',
						icon: 'none'
					})
				}

				// 简化错误记录
				console.error('订单详情加载错误详情:', {
					message: error.message,
					orderId: this.orderId,
					retryCount: this.retryCount,
					timestamp: new Date().toISOString()
				})
			} finally {
				if (this._isComponentActive) {
					await simpleUpdate(this, {
						loading: false
					})
				}
			}
		},

		// 安全获取订单数据
		safeGetOrderData(field, defaultValue = '') {
			return safeGetOrderData(this.order, field, defaultValue)
		},

		formatTime(time) {
			return formatOrderTime(time, 'datetime')
		},

		formatAmount(amount) {
			return formatOrderAmount(amount)
		},

		// 获取商品图片
		getItemImage(item) {
			const productImages = this.safeGetOrderData(`items.${this.orderItems.indexOf(item)}.product.images`, [])
			const productImageUrl = this.safeGetOrderData(`items.${this.orderItems.indexOf(item)}.product.imageUrl`,
				'')

			if (productImageUrl) return productImageUrl
			if (productImages.length > 0) return productImages[0]
			return '/static/icons/default-product.png'
		},

		// 获取商品名称
		getItemName(item) {
			return safeGetOrderData(item, 'productName') ||
				safeGetOrderData(item, 'product.name', '未知商品')
		},

		// 获取商品规格
		getItemSpecs(item) {
			const specs = safeGetOrderData(item, 'specifications', {})
			return Object.keys(specs).length > 0 ? specs : null
		},

		// 获取商品数量
		getItemQuantity(item) {
			return safeGetOrderData(item, 'quantity', 0)
		},

		// 获取商品单价
		getItemUnitPrice(item) {
			return safeGetOrderData(item, 'unitPrice', 0)
		},

		// 获取商品总价
		getItemTotalPrice(item) {
			return safeGetOrderData(item, 'totalPrice', 0)
		},

		// 获取配送费
		getDeliveryFee() {
			return this.safeGetOrderData('deliveryInfo.deliveryFee', 0)
		},

		// 获取折扣金额
		getDiscountAmount() {
			return this.safeGetOrderData('discountAmount', 0)
		},

		// 获取使用积分
		getPointsUsed() {
			return this.safeGetOrderData('pointsUsed', 0)
		},

		// 获取获得积分
		getPointsEarned() {
			return this.safeGetOrderData('pointsEarned', 0)
		},

		// 获取总积分
		getTotalPoints() {
			return this.safeGetOrderData('totalPoints', 0)
		},

		// 处理图片加载错误
		handleImageError(e) {
			console.log('图片加载失败:', e)
			// 可以设置默认图片
		},

		// 返回上一页
		goBack() {
			uni.navigateBack({
				delta: 1
			})
		},

		// 重试加载
		retryLoad() {
			if (this.retryCount < this.maxRetries) {
				this.loadOrderDetail()
			} else {
				uni.showModal({
					title: '加载失败',
					content: '多次尝试加载失败，请检查网络连接后重试',
					showCancel: false
				})
			}
		},

		// 显示订单二维码
		async showOrderQRCode() {
			if (!this.canShowQRCode) {
				uni.showToast({
					title: '当前订单状态不支持二维码',
					icon: 'none'
				})
				return
			}

			try {
				uni.showLoading({ title: '生成二维码中...' })

				// 获取订单二维码
				const response = await getOrderQRCode(this.orderId, {
					size: 400,
					format: 'base64'
				})

				if (response.success) {
					await simpleUpdate(this, {
						showQRCode: true,
						qrCodeData: response.data
					})
				} else {
					throw new Error(response.message || '获取二维码失败')
				}
			} catch (error) {
				console.error('显示二维码失败:', error)
				uni.showToast({
					title: error.message || '显示二维码失败',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		},

		// 关闭二维码
		closeQRCode() {
			simpleUpdate(this, {
				showQRCode: false,
				qrCodeData: null
			})
		},

		// 刷新二维码
		async refreshQRCode() {
			try {
				uni.showLoading({ title: '刷新中...' })

				const response = await refreshOrderQRCode(this.orderId)

				if (response.success) {
					// 重新获取二维码
					const qrResponse = await getOrderQRCode(this.orderId, {
						size: 400,
						format: 'base64'
					})

					if (qrResponse.success) {
						await simpleUpdate(this, {
							qrCodeData: qrResponse.data
						})
						uni.showToast({
							title: '二维码已刷新',
							icon: 'success'
						})
					}
				} else {
					throw new Error(response.message || '刷新失败')
				}
			} catch (error) {
				console.error('刷新二维码失败:', error)
				uni.showToast({
					title: error.message || '刷新失败',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		},

		// 保存二维码到相册
		async saveQRCode() {
			if (!this.qrCodeData || !this.qrCodeData.image) {
				uni.showToast({
					title: '二维码数据不存在',
					icon: 'none'
				})
				return
			}

			try {
				uni.showLoading({ title: '保存中...' })

				// 将base64转换为临时文件
				const base64Data = this.qrCodeData.image
				const filePath = `${uni.env.USER_DATA_PATH}/qr_${this.orderId}_${Date.now()}.png`

				// 写入文件
				const fs = uni.getFileSystemManager()
				fs.writeFileSync(filePath, base64Data, 'base64')

				// 保存到相册
				await uni.saveImageToPhotosAlbum({
					filePath: filePath
				})

				uni.showToast({
					title: '已保存到相册',
					icon: 'success'
				})
			} catch (error) {
				console.error('保存二维码失败:', error)
				if (error.errMsg && error.errMsg.includes('auth deny')) {
					uni.showModal({
						title: '权限不足',
						content: '需要相册权限才能保存图片，请在设置中开启',
						showCancel: false
					})
				} else {
					uni.showToast({
						title: '保存失败',
						icon: 'none'
					})
				}
			} finally {
				uni.hideLoading()
			}
		},

		async cancelOrder() {
			console.log('=== 订单详情页面：开始取消订单流程 ===')
			console.log('订单ID:', this.orderId)
			console.log('订单数据:', this.order)
			
			// 验证订单ID
			if (!this.orderId) {
				console.error('订单ID不存在')
				uni.showToast({
					title: '订单ID不存在',
					icon: 'none'
				})
				return
			}

			// 验证订单状态
			const orderStatus = this.safeGetOrderData('status')
			console.log('当前订单状态:', orderStatus)
			console.log('是否可以取消:', this.canCancelOrder)
			
			if (!this.canCancelOrder) {
				console.error('订单状态不允许取消:', orderStatus)
				uni.showToast({
					title: '当前订单状态不允许取消',
					icon: 'none'
				})
				return
			}

			// 使用 Promise 方式处理 showModal
			const isConfirmed = await new Promise((resolve) => {
				uni.showModal({
					title: '确认取消',
					content: '确定要取消这个订单吗？取消后积分将退还到您的账户。',
					confirmText: '确认取消',
					cancelText: '我再想想',
					success: (res) => {
						console.log('showModal success 回调:', res)
						resolve(res.confirm === true)
					},
					fail: () => {
						console.log('showModal fail 回调')
						resolve(false)
					}
				})
			})

			if (!isConfirmed) {
				console.log('用户取消了操作')
				return
			}

			console.log('用户确认取消订单')
			uni.showLoading({ title: '取消中...' })

			try {
				console.log('调用取消订单API，订单ID:', this.orderId)
				const response = await cancelOrder(this.orderId, '用户主动取消')
				console.log('取消订单API响应:', response)

				if (response && response.success) {
					console.log('订单取消成功')
					uni.showToast({
						title: '订单已取消',
						icon: 'success'
					})
					// 重新加载订单详情
					console.log('重新加载订单详情')
					await this.loadOrderDetail()
				} else {
					const errorMsg = response?.message || '取消订单失败'
					console.error('取消订单失败:', errorMsg)
					throw new Error(errorMsg)
				}
			} catch (error) {
				console.error('取消订单异常:', error)
				uni.showToast({
					title: error.message || '取消失败',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
				console.log('=== 订单详情页面：取消订单流程结束 ===')
			}
		},

		reorder() {
			const items = this.order.items.map(item => ({
				productId: item.productId._id,
				quantity: item.quantity,
				specifications: item.specifications
			}))

			uni.setStorageSync('reorderItems', items)
			uni.switchTab({
				url: '/pages/print/index'
			})
		}
	}
}
</script>

<style scoped>
.order-detail-page {
	padding: 0;
	background: linear-gradient(180deg, #f8f9fa 0%, #f5f5f5 100%);
	min-height: 100vh;
}

.header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 40rpx 30rpx 30rpx;
	background: #fff;
	border-bottom: 1rpx solid #f0f0f0;
	margin-bottom: 20rpx;
}

.title {
	font-size: 38rpx;
	font-weight: 600;
	color: #1a1a1a;
	letter-spacing: 1rpx;
}

.qr-btn {
	padding: 16rpx 28rpx;
	background: linear-gradient(135deg, #007aff, #0056cc);
	color: white;
	border-radius: 24rpx;
	font-size: 24rpx;
	font-weight: 500;
	box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
	transition: all 0.2s ease;
}

.qr-btn:active {
	transform: scale(0.95);
	box-shadow: 0 2rpx 8rpx rgba(0, 122, 255, 0.4);
}

.qr-text {
	color: white;
}

.order-content {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.info-section,
.items-section,
.delivery-section,
.cost-section,
.points-section,
.notes-section {
	background: white;
	border-radius: 16rpx;
	padding: 32rpx;
	margin: 0 20rpx 20rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
	border: 1rpx solid #f5f5f5;
}

.section-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #1a1a1a;
	margin-bottom: 24rpx;
	padding-bottom: 16rpx;
	border-bottom: 2rpx solid #f0f0f0;
	display: flex;
	justify-content: space-between;
	align-items: center;
	letter-spacing: 0.5rpx;
}

.item-count {
	font-size: 24rpx;
	color: #999;
	font-weight: normal;
}

.info-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16rpx;
}

.info-item:last-child {
	margin-bottom: 0;
}

.label {
	font-size: 28rpx;
	color: #666;
}

.value {
	font-size: 28rpx;
	color: #333;
	text-align: right;
	flex: 1;
	margin-left: 20rpx;
	word-break: break-all;
}

.selectable {
	user-select: text;
}

.reservation-code {
	font-family: monospace;
	font-weight: bold;
	color: #007aff;
}

.address {
	text-align: right;
	line-height: 1.4;
}

.final-amount {
	font-size: 32rpx;
	font-weight: bold;
}

.status-pending {
	color: #fa8c16;
}

.status-confirmed {
	color: #1890ff;
}

.status-processing,
.status-printing {
	color: #722ed1;
}

.status-completed {
	color: #52c41a;
}

.status-cancelled {
	color: #ff4d4f;
}

.payment-unpaid {
	color: #fa8c16;
}

.payment-paid {
	color: #52c41a;
}

.payment-refunded {
	color: #ff4d4f;
}

.item {
	display: flex;
	gap: 20rpx;
	margin-bottom: 20rpx;
	padding-bottom: 20rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.item:last-child {
	margin-bottom: 0;
	padding-bottom: 0;
	border-bottom: none;
}

.item-image {
	width: 100rpx;
	height: 100rpx;
	border-radius: 8rpx;
	flex-shrink: 0;
}

.items-list {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.item-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.item-name {
	font-size: 28rpx;
	color: #333;
	font-weight: bold;
	line-height: 1.3;
}

.item-specs {
	display: flex;
	flex-wrap: wrap;
	gap: 8rpx;
}

.item-spec {
	font-size: 22rpx;
	color: #666;
	background: #f5f5f5;
	padding: 4rpx 8rpx;
	border-radius: 4rpx;
}

.item-pricing {
	display: flex;
	flex-direction: column;
	gap: 4rpx;
}

.item-quantity,
.item-price {
	font-size: 24rpx;
	color: #999;
}

.item-total {
	font-size: 28rpx;
	color: #ff4d4f;
	font-weight: bold;
}

.empty-items {
	text-align: center;
	padding: 40rpx;
	color: #999;
}

.empty-text {
	font-size: 28rpx;
}

.cost-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16rpx;
}

.cost-item:last-child {
	margin-bottom: 0;
}

.cost-item.total {
	padding-top: 16rpx;
	border-top: 1rpx solid #f0f0f0;
	font-weight: bold;
}

.cost-item.total .value {
	color: #ff4d4f;
	font-size: 32rpx;
}

.discount {
	color: #52c41a;
}

.actions {
	display: flex;
	gap: 16rpx;
	margin: 30rpx 20rpx 40rpx;
	flex-wrap: wrap;
}

.cancel-btn,
.reorder-btn,
.qr-btn-action {
	flex: 1;
	min-width: 200rpx;
	padding: 28rpx 24rpx;
	border-radius: 28rpx;
	font-size: 30rpx;
	font-weight: 500;
	border: none;
	transition: all 0.2s ease;
	letter-spacing: 1rpx;
}

.cancel-btn:active,
.reorder-btn:active,
.qr-btn-action:active {
	transform: scale(0.95);
}

.cancel-btn:disabled,
.reorder-btn:disabled,
.qr-btn-action:disabled {
	opacity: 0.6;
	transform: none;
}

.cancel-btn {
	background: linear-gradient(135deg, #ff6b6b, #ee5a52);
	color: white;
	box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.3);
}

.cancel-btn:active {
	background: linear-gradient(135deg, #ee5a52, #dc4c41);
	box-shadow: 0 2rpx 8rpx rgba(255, 107, 107, 0.4);
}

.reorder-btn {
	background: linear-gradient(135deg, #007aff, #0056cc);
	color: white;
	box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
}

.reorder-btn:active {
	background: linear-gradient(135deg, #0056cc, #004499);
	box-shadow: 0 2rpx 8rpx rgba(0, 122, 255, 0.4);
}

.qr-btn-action {
	background: linear-gradient(135deg, #52c41a, #389e0d);
	color: white;
	box-shadow: 0 4rpx 12rpx rgba(82, 196, 26, 0.3);
}

.qr-btn-action:active {
	background: linear-gradient(135deg, #389e0d, #237804);
	box-shadow: 0 2rpx 8rpx rgba(82, 196, 26, 0.4);
}

/* 加载状态 */
.loading {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 80rpx;
	color: #999;
}

.loading-spinner {
	width: 60rpx;
	height: 60rpx;
	border: 4rpx solid #f0f0f0;
	border-top: 4rpx solid #007aff;
	border-radius: 50%;
	animation: spin 1s linear infinite;
	margin-bottom: 20rpx;
}

.loading-text {
	font-size: 28rpx;
}

@keyframes spin {
	0% {
		transform: rotate(0deg);
	}

	100% {
		transform: rotate(360deg);
	}
}

/* 错误状态 */
.error-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 80rpx;
	text-align: center;
}

.error-icon {
	font-size: 80rpx;
	margin-bottom: 20rpx;
}

.error-message {
	font-size: 28rpx;
	color: #ff4d4f;
	margin-bottom: 30rpx;
	line-height: 1.4;
}

.retry-btn,
.back-btn {
	padding: 20rpx 40rpx;
	background: #007aff;
	color: white;
	border-radius: 8rpx;
	font-size: 28rpx;
	border: none;
}

/* 空状态 */
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 80rpx;
	text-align: center;
}

.empty-icon {
	font-size: 80rpx;
	margin-bottom: 20rpx;
}

.empty-message {
	font-size: 28rpx;
	color: #999;
	margin-bottom: 30rpx;
}

/* 积分样式 */
.points-used {
	color: #fa8c16;
}

.points-earned {
	color: #52c41a;
}

/* 备注样式 */
.notes-item {
	flex-direction: column;
	align-items: flex-start;
	gap: 8rpx;
}

.notes-text {
	text-align: left;
	line-height: 1.4;
	margin-left: 0;
}

.admin-notes {
	color: #666;
	font-style: italic;
}

/* 二维码弹窗 */
.qr-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.7);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 1000;
	backdrop-filter: blur(4rpx);
}

.qr-content {
	background: white;
	border-radius: 24rpx;
	padding: 48rpx;
	margin: 40rpx;
	max-width: 640rpx;
	width: 100%;
	box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.3);
	animation: qr-modal-show 0.3s ease-out;
}

@keyframes qr-modal-show {
	from {
		opacity: 0;
		transform: scale(0.8) translateY(40rpx);
	}

	to {
		opacity: 1;
		transform: scale(1) translateY(0);
	}
}

.qr-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 32rpx;
}

.qr-title {
	font-size: 34rpx;
	font-weight: 600;
	color: #1a1a1a;
	letter-spacing: 1rpx;
}

.qr-close {
	font-size: 48rpx;
	color: #999;
	line-height: 1;
	padding: 12rpx;
	border-radius: 50%;
	transition: all 0.2s ease;
}

.qr-close:active {
	background: #f5f5f5;
	color: #666;
}

.qr-body {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 20rpx;
}

.qr-canvas {
	width: 400rpx;
	height: 400rpx;
	border: 1rpx solid #f0f0f0;
	border-radius: 8rpx;
}

.qr-tip {
	font-size: 28rpx;
	color: #666;
	text-align: center;
}

.qr-order-info {
	font-size: 24rpx;
	color: #999;
	text-align: center;
}

.qr-actions {
	margin-top: 30rpx;
	display: flex;
	justify-content: center;
}

.qr-save-btn {
	padding: 20rpx 40rpx;
	background: #007aff;
	color: white;
	border-radius: 8rpx;
	font-size: 28rpx;
	border: none;
}

.qr-image-container {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 32rpx;
	background: linear-gradient(135deg, #f8f9fa, #ffffff);
	border-radius: 20rpx;
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
	border: 2rpx solid #f0f0f0;
}

.qr-image {
	width: 400rpx;
	height: 400rpx;
	border-radius: 12rpx;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.qr-placeholder {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	width: 400rpx;
	height: 400rpx;
	border: 2rpx dashed #ddd;
	border-radius: 8rpx;
	background: #f9f9f9;
}

.qr-placeholder-text {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 20rpx;
}

.qr-info {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 8rpx;
	margin-top: 20rpx;
	padding: 20rpx;
	background: #f8f9fa;
	border-radius: 8rpx;
}

.qr-order-info,
.qr-amount-info {
	font-size: 26rpx;
	color: #333;
	font-weight: bold;
}

.qr-tip {
	font-size: 24rpx;
	color: #666;
	text-align: center;
	line-height: 1.4;
}

.qr-actions {
	display: flex;
	gap: 16rpx;
	margin-top: 32rpx;
}

.qr-refresh-btn,
.qr-save-btn {
	flex: 1;
	padding: 24rpx 20rpx;
	border-radius: 24rpx;
	font-size: 28rpx;
	font-weight: 500;
	border: none;
	transition: all 0.2s ease;
	letter-spacing: 0.5rpx;
}

.qr-refresh-btn:active,
.qr-save-btn:active {
	transform: scale(0.95);
}

.qr-refresh-btn {
	background: linear-gradient(135deg, #f5f5f5, #e8e8e8);
	color: #666;
	border: 1rpx solid #ddd;
}

.qr-refresh-btn:active {
	background: linear-gradient(135deg, #e8e8e8, #ddd);
}

.qr-save-btn {
	background: linear-gradient(135deg, #007aff, #0056cc);
	color: white;
	box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
}

.qr-save-btn:active {
	background: linear-gradient(135deg, #0056cc, #004499);
	box-shadow: 0 2rpx 8rpx rgba(0, 122, 255, 0.4);
}
</style>